package com.example.dangerouscargodriver.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.baiju.bjpopupwindow.view.BottomDialog;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.ImageUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

public class EnterPlatformPersonalStepOneActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "EnterPlatform";

    private static final int ACTION_TRANSPORT_LICENSE_OFFSET = 0;
    private static final int ACTION_EMPLOYEE_LICENSE_OFFSET = 1;
    private static final int ACTION_QUALIFICATION_CERTIFICATE_OFFSET = 2;
    private static final int ACTION_DRIVER_LICENSE_OFFSET = 3;

    //相册请求码
    private static final int ALBUM_REQUEST_CODE = 1;
    //相机请求码
    private static final int CAMERA_REQUEST_CODE = 2;

    private static final int SELECT_TRANSPORT_LICENSE = 0;
    private static final int SELECT_EMPLOYEE_LICENSE = 1;
    private static final int SELECT_QUALIFICATION_CERTIFICATE = 2;
    private static final int SELECT_DRIVER_LICENSE = 3;

    private ActionBar mActionBar = null;
    private Button mCommit = null;
    private LinearLayout mLayoutTransportLicense = null;
    private ImageView mIvTransportLicense = null;
    private ImageView mIvTransportLicenseLoading = null;
    private boolean mIvTransportLicenseUpload = false;

    private LinearLayout mLayoutEmployeeLicense = null;
    private ImageView mIvEmployeeLicense = null;
    private ImageView mIvEmployeeLicenseLoading = null;
    private boolean mIvEmployeeLicenseUpload = false;

    private LinearLayout mLayoutCertificate = null;
    private ImageView mIvQualificationCertificate = null;
    private ImageView mIvQualificationCertificateLoading = null;
    private boolean mIvQualificationCertificateUpload = false;

    private LinearLayout mLayoutDriverLicense = null;
    private ImageView mIvDriverLicense = null;
    private ImageView mIvDriverLicenseLoading = null;
    private boolean mIvDriverLicenseUpload = false;

    private BottomDialog mBottomDialog = null;

    //调用照相机返回图片文件
    private File mTempFile;

    private int mSelectType = SELECT_TRANSPORT_LICENSE;
    private HashMap<String, String> mSelectPicture = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(EnterPlatformPersonalStepOneActivity.class);
        AppManager.getAppManager().addActivity(this);

        setContentView(R.layout.activity_enter_platform_personal_step_one);

        mSelectPicture = new HashMap<>();

        mLayoutTransportLicense = findViewById(R.id.layout_transport_license);
        mIvTransportLicense = findViewById(R.id.iv_transport_license);
        mLayoutTransportLicense.setOnClickListener(this);
        mIvTransportLicenseLoading = findViewById(R.id.iv_transport_license_loading);

        mLayoutEmployeeLicense = findViewById(R.id.layout_employment_license);
        mIvEmployeeLicense = findViewById(R.id.iv_employment_license);
        mLayoutEmployeeLicense.setOnClickListener(this);
        mIvEmployeeLicenseLoading = findViewById(R.id.iv_employment_license_loading);

        mLayoutCertificate = findViewById(R.id.layout_qualification_certificate);
        mIvQualificationCertificate = findViewById(R.id.iv_qualification_certificate);
        mLayoutCertificate.setOnClickListener(this);
        mIvQualificationCertificateLoading = findViewById(R.id.iv_qualification_certificate_loading);

        mLayoutDriverLicense = findViewById(R.id.layout_driver_license);
        mIvDriverLicense = findViewById(R.id.iv_driver_license);
        mLayoutDriverLicense.setOnClickListener(this);
        mIvDriverLicenseLoading = findViewById(R.id.iv_driver_license_loading);

        mCommit = findViewById(R.id.btn_add_bill);
        mCommit.setOnClickListener(this);

        mBottomDialog = new BottomDialog();
        mBottomDialog.setOnItemClickListener(new BottomDialog.OnItemClickListener() {
            @Override
            public void onCamera() {
                getPicFromCamera();
            }

            @Override
            public void onAlbum() {
                getPicFromAlbum();
            }

            @Override
            public void onCancel() {

            }
        });

        mActionBar = findViewById(R.id.actionEnterPlatformPersonalStepOne);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getPicFromAlbum() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
    }

    private void getPicFromCamera(){
        mTempFile = new File(Environment.getExternalStorageDirectory() +
                File.separator + "vsiji" + File.separator
                + "Pictures", System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this,
                    "com.example.dangerouscargodriver.fileprovider",
                    mTempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        }

        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_add_bill){
            if(checkFileUploadResult()){
                Intent intent = new Intent(this, EnterPlatformPersonalStepTwoActivity.class);
                intent.putExtra("info", mSelectPicture);
                startActivity(intent);
            }
            else{
                ToastUtils.showLongToast(this, "请上传完整图片信息！");
            }
        }
        else if(v.getId() == R.id.layout_transport_license){
            mSelectType = SELECT_TRANSPORT_LICENSE;
            mBottomDialog.showDialog(EnterPlatformPersonalStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_employment_license){
            mSelectType = SELECT_EMPLOYEE_LICENSE;
            mBottomDialog.showDialog(EnterPlatformPersonalStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_qualification_certificate){
            mSelectType = SELECT_QUALIFICATION_CERTIFICATE;
            mBottomDialog.showDialog(EnterPlatformPersonalStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_driver_license){
            mSelectType = SELECT_DRIVER_LICENSE;
            mBottomDialog.showDialog(EnterPlatformPersonalStepOneActivity.this);
        }
        else{

        }
    }

    private boolean checkFileUploadResult() {
        return mIvTransportLicenseUpload &&
            mIvEmployeeLicenseUpload &&
            mIvQualificationCertificateUpload &&
            mIvDriverLicenseUpload;
    }

    private void pushFileToRemote(String file, int action){
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        sendHttpMultipartRequest(
                RemoteAPI.REQUEST_UPLOAD_FILE,
                header,
                null,
                file,
                action);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == RESULT_OK) {
                    Bitmap bitmap = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(this,
                                "com.example.dangerouscargodriver.fileprovider",
                                mTempFile);
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(mTempFile);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        bitmap = BitmapFactory.decodeStream(fis);
                        bitmap = ImageUtils.extractMiniThumb(bitmap, 232, 155);
                    }
                    else {
                        bitmap = BitmapFactory.decodeFile(mTempFile.getPath());
                    }
                    if(mSelectType == SELECT_TRANSPORT_LICENSE) {
                        mIvTransportLicense.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("transportLicense")){
                            mSelectPicture.remove("transportLicense");
                        }
                        mSelectPicture.put("transportLicense", mTempFile.getPath());
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_TRANSPORT_LICENSE_OFFSET);
                        startAnimation(mIvTransportLicenseLoading);
                    }
                    else if(mSelectType == SELECT_EMPLOYEE_LICENSE){
                        mIvEmployeeLicense.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("employeeLicense")){
                            mSelectPicture.remove("employeeLicense");
                        }
                        mSelectPicture.put("employeeLicense", mTempFile.getPath());
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_EMPLOYEE_LICENSE_OFFSET);
                        startAnimation(mIvEmployeeLicenseLoading);
                    }
                    else if(mSelectType == SELECT_QUALIFICATION_CERTIFICATE){
                        mIvQualificationCertificate.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("qualificationCertificate")){
                            mSelectPicture.remove("qualificationCertificate");
                        }
                        mSelectPicture.put("qualificationCertificate", mTempFile.getPath());
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_QUALIFICATION_CERTIFICATE_OFFSET);
                        startAnimation(mIvQualificationCertificateLoading);
                    }
                    else{
                        mIvDriverLicense.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("driverLicense")){
                            mSelectPicture.remove("driverLicense");
                        }
                        mSelectPicture.put("driverLicense", mTempFile.getPath());
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_DRIVER_LICENSE_OFFSET);
                        startAnimation(mIvDriverLicenseLoading);
                    }
                }
                break;
            case ALBUM_REQUEST_CODE:    //调用相册后返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    String file = ImageUtils.getRealPathFromURI(uri, this);
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    bitmap = ImageUtils.extractMiniThumb(bitmap, 320, 160);
                    if(mSelectType == SELECT_TRANSPORT_LICENSE) {
                        mIvTransportLicense.setImageBitmap(bitmap);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_TRANSPORT_LICENSE_OFFSET);
                        startAnimation(mIvTransportLicenseLoading);
                    }
                    else if(mSelectType == SELECT_EMPLOYEE_LICENSE){
                        mIvEmployeeLicense.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("employeeLicense")){
                            mSelectPicture.remove("employeeLicense");
                        }
                        mSelectPicture.put("employeeLicense", file);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_EMPLOYEE_LICENSE_OFFSET);
                        startAnimation(mIvEmployeeLicenseLoading);
                    }
                    else if(mSelectType == SELECT_QUALIFICATION_CERTIFICATE){
                        mIvQualificationCertificate.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("qualificationCertificate")){
                            mSelectPicture.remove("qualificationCertificate");
                        }
                        mSelectPicture.put("qualificationCertificate", file);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_QUALIFICATION_CERTIFICATE_OFFSET);
                        startAnimation(mIvQualificationCertificateLoading);
                    }
                    else{
                        mIvDriverLicense.setImageBitmap(bitmap);
                        if(mSelectPicture.containsKey("driverLicense")){
                            mSelectPicture.remove("driverLicense");
                        }
                        mSelectPicture.put("driverLicense", file);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_DRIVER_LICENSE_OFFSET);
                        startAnimation(mIvDriverLicenseLoading);
                    }
                }
                break;
        }
    }

    private void startAnimation(ImageView imageView){
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);

        Animation rotateAnimation = AnimationUtils.loadAnimation(getBaseContext(),
                R.anim.anim_circle_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();
        rotateAnimation.setInterpolator(interpolator);
        imageView.startAnimation(rotateAnimation);
        imageView.setVisibility(View.VISIBLE);
    }

    private void stopAnimation(ImageView imageView){
        imageView.clearAnimation();
        imageView.setImageResource(R.drawable.ic_upload_done);
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_TRANSPORT_LICENSE_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mIvTransportLicenseLoading);
                    mIvTransportLicenseUpload = true;
                    if(mSelectPicture.containsKey("transportLicense")){
                        mSelectPicture.remove("transportLicense");
                    }
                    mSelectPicture.put("transportLicense", res.getJSONObject("data").getString("url"));
                }
            }
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_EMPLOYEE_LICENSE_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mIvEmployeeLicenseLoading);
                    mIvEmployeeLicenseUpload = true;
                    if(mSelectPicture.containsKey("employeeLicense")){
                        mSelectPicture.remove("employeeLicense");
                    }
                    mSelectPicture.put("employeeLicense", res.getJSONObject("data").getString("url"));
                }
            }
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_QUALIFICATION_CERTIFICATE_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mIvQualificationCertificateLoading);
                    mIvQualificationCertificateUpload = true;
                    if(mSelectPicture.containsKey("qualificationCertificate")){
                        mSelectPicture.remove("qualificationCertificate");
                    }
                    mSelectPicture.put("qualificationCertificate", res.getJSONObject("data").getString("url"));
                }
            }
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_DRIVER_LICENSE_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mIvDriverLicenseLoading);
                    mIvDriverLicenseUpload = true;
                    if(mSelectPicture.containsKey("driverLicense")){
                        mSelectPicture.remove("driverLicense");
                    }
                    mSelectPicture.put("driverLicense", res.getJSONObject("data").getString("url"));
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {

    }
}